# -!- coding: utf-8 -!-
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#作者：cacho_37967865
#博客：https://blog.csdn.net/sinat_37967865
#文件：paramiko_model.py
#日期：2020-03-12
#备注：paramiko是用python语言写的一个模块，遵循SSH2协议，支持以加密和认证的方式，进行远程服务器的连接。
    先安装cryptography  pip install --user -I cryptography   然后：pip install paramiko
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

import os
from datetime import datetime
import paramiko
from pycacho.cachobase.files_select import get_files
from pycacho.cachobase.logger import Logger
logger = Logger("paramiko_model").get_log()


class SftpDeal():
    def __init__(self,ip,username,password):
        self.hostname = ip
        self.username = username                # mstest
        self.password = password               # msydtest
        self.port = 22
        try:
            self.conn = paramiko.Transport((self.hostname, self.port))            # 获取Transport实例
            self.conn.connect(username=self.username, password=self.password)     # 连接SSH服务端，使用password
            self.sftp_ob = paramiko.SFTPClient.from_transport(self.conn)          # 获取SFTP实例
        except Exception as e:
            print(e)

    # 上传文件，local_file-本地目录；remote_path-远程目录
    def upload(self,local_file,remote_file):
        try:
            self.sftp_ob.put(local_file, remote_file)
        except Exception as e:
            self.sftp_ob.mkdir(os.path.split(remote_file)[0])
            self.sftp_ob.put(local_file, remote_file)
            print("从本地： %s 上传到： %s" % (local_file, remote_file))
        print(remote_file + ' 文件上传成功 %s ' % datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        #self.conn.close()

    def download(self,remote_file,local_file):
        try:
            self.sftp_ob.get(remote_file,local_file)
        except Exception as e:
            self.sftp_ob.mkdir(os.path.dirname(local_file))
            print("从服务器： %s 下载到： %s" % (remote_file,local_file ))
            print(e)
        print(remote_file,'文件下载成功 %s ' % datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        #self.conn.close()

    def remove(self,remote_file):
        try:
            self.sftp_ob.remove(remote_file)
            print(remote_file + ' 文件删除成功 %s ' % datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        except:
            print('服务器上面无文件：%s'% (remote_file))
        #self.conn.close()

    # 递归创建文件夹  remote_base：基础目录；  dir_list：递归目录名称-->list格式
    def batch_mkdir(self,remote_base,dir_list):
        remote_path = remote_base
        for dir in dir_list:
            remote_path = remote_path + dir + '/'
            try:
                self.sftp_ob.stat(remote_path)
                print(remote_path,' 文件目录已存在！')
            except Exception as e:
                self.sftp_ob.mkdir(remote_path)
                print('服务器上面创建成功的目录：%s '% (remote_path))
        return remote_path


    # 批量上传文件 local_path：本地文件目录， type需要上传的文件类型，remote_path 远程目录
    def batch_upload(self,local_path,type,remote_path):
        files = get_files(local_path, type)
        for local_file in files:
            remote_file = remote_path + os.path.split(local_file)[1]
            #print(local_file,remote_file)
            self.upload(local_file,remote_file)


if __name__ == '__main__':
    sftp = SftpDeal('10.16.20.217','mstest','msydtest')
    local_path = 'E:\zenglingwei\\test\\batch\\'
    remote_base = '/data/sftp/hb/home/upload/hb/send/'
    remote_path = sftp.batch_mkdir(remote_base, ['credit','2020','11'])
    sftp.batch_upload(local_path,'jpg',remote_path)
    #sftp.batch_upload(local_path,'jpg',remote_path)
    #sftp.upload(local_file, remote_path)
    #sftp.download(remote_path, local_file)
    #sftp.remove(remote_path)